using System;
using System.Collections.Generic;
using System.IO;
using CYZHAPI.Common;
using CYZHAPI.Common.Config;
using CYZHAPI.Common.tools;
using CYZHAPI.Middlewares;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Net.Http.Headers;

namespace CYZHAPI.web.Controllers {
    public class fileController : BaseController {
        //private IHostingEnvironment _hostingEnvironment;
        private IHttpContextAccessor _accessor;
        private WebApiOption _Config;
        public fileController (IHttpContextAccessor accessor, IOptions<WebApiOption> option, ILogger<fileController> logger) : base (logger) {
            //this._hostingEnvironment = env; ---IHostingEnvironment env, 
            _accessor = accessor;
            _Config = option.Value;
        }

        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        [HttpPost]
        public BaseResponseResult post (/*string filetype,List<IFormFile> IFormFilefile*/ ) {
            HttpContext context = _accessor.HttpContext;
            string filetype = _accessor.HttpContext.Request.Form["filetype"];
            string filetime = _accessor.HttpContext.Request.Form["filetime"];
            IFormFileCollection obj_Files = _accessor.HttpContext.Request.Form.Files;
            if(obj_Files.Count == 0 ) 
                return  new BaseResponseResult(){
                        code = "901",
                        message = "缺少上传的文件"
                    };
            for(int i = 0; i<obj_Files.Count; i++)
            {
                IFormFile upload_file = obj_Files[i];
                // 文件大小
                long size = 0;
                // 原文件名（包括路径）
                var filename = ContentDispositionHeaderValue.Parse (upload_file.ContentDisposition).FileName.
                    ToString().Replace ("\"", "");
                // 扩展名
                //var extName = filename.Substring (filename.LastIndexOf ('.')).Replace ("\"", "");
                // 新文件名
                //string shortfilename = "test" + extName;
                // 新文件名（包括路径）_hostingEnvironment.WebRootPath 
                string sfilepath = EntityKeyToValue.getProperties<PathOption>(_Config.Path,filetype) + @"\"+filetime;
                string file_name = sfilepath + @"\" + filename;
                // 设置文件大小
                //size += upload_file.Length;
                // 创建新文件
                try
                {
                    if(Directory.Exists(sfilepath) == false)//如果不存在就创建file文件夹
                    {
                        Directory.CreateDirectory(sfilepath);
                    }
                    //Directory.Delete(Server.MapPath("~/upimg/hufu"), true);//删除文件夹以及文件夹中的子目录，文件    
                    //判断文件的存在
                    if (System.IO.File.Exists(file_name))
                    {
                        //文件存在删除文件
                        System.IO.File.Delete(file_name);
                    }
                    using (FileStream fs = System.IO.File.Create (file_name))
                    {
                        // 复制文件
                        upload_file.CopyTo (fs);
                        // 清空缓冲区数据
                        fs.Flush ();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    return  new BaseResponseResult(){
                        code = "901",
                        message = "文件上传错误，无法保存"
                    };
                }
            }
            return new BaseResponseResult(){
                code = "200",
                message = "文件上传成功"
            };
        }
        
    }

}